//  肝脏移植检查
//  YZEGanzangCheckViewController.m
//  yilutongxing
//
//  Created by T&J on 2017/6/6.
//  Copyright © 2017年 YZE. All rights reserved.
//
#import <QMUITips.h>
#import <ActionSheetCustomPicker.h>
#import "CommonDefine.h"
#import "IQActionSheetPickerView.h"
#import "DzyImgPicker.h"
#import "DataUtils.h"
#import "PYSearchViewController.h"
#import "YZEGanzangCheckViewController.h"
#import "RoutineBloodViewController.h"
#import "LiverViewController.h"
#import "RenalViewController.h"
#import "BloodsugarViewController.h"
#import "BloodfatViewController.h"
#import "ElectrolyteViewController.h"
#import "HepatitisVirusViewController.h"
#import "TumorMarkerViewController.h"
#import "ImSupViewController.h"
#import "LiverTranSonoViewController.h"
#import "SinglelineTextFormViewController.h"
#import "RPUserInfoBean.h"
#import "RadioButtonManager.h"
#import "RPLiverCheckBean.h"
#import "TabletPlanViewController.h"

#define URL_GetGraftingcheckdata @"/api/liverGraftingCheck"
#define URL_SearchHospital @"/api/_search/hospitals?query=" //搜索医院接口
#define URL_SuggestionHospital @"/api/commonhospitals" //搜索医院界面中的建议数据接口

@interface YZEGanzangCheckViewController ()<NetworkUtilsDelegate, DzyImgDelegate, ActionSheetCustomPickerDelegate, IQActionSheetPickerViewDelegate,
                                            PYSearchViewControllerDelegate, PYSearchViewControllerDataSource,
                                            SinglelineTextFormViewControllerDelegate, TabletPlanViewBackDelegate,
                                            RoutineBloodViewControllerDelegate, LiverViewControllerDelegate, RenalViewControllerDelegate, BloodsugarViewControllerDelegate,
                                            BloodfatViewControllerDelegate, ElectrolyteViewControllerDelegate,
                                            HepatitisVirusViewControllerDelegate, TumorMarkerViewControllerDelegate,
                                            ImSupViewControllerDelegate, LiverTranSonoViewControllerDelegate>

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *optypeBtnArr;
@property (strong, nonatomic) RadioButtonManager *m1;//管理器官来源按钮组
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *graftingstandardBtnArr;
@property (strong, nonatomic) RadioButtonManager *m2;//管理手术方式按钮组
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *fitypeBtnArr;
@property (strong, nonatomic) RadioButtonManager *m3;//管理胆管吻合方式按钮组
@property (strong, nonatomic) IBOutlet UITableViewCell *ophospitalCell;

@property (nonatomic, strong) NSArray *genderArr;
@property (nonatomic, strong) NSMutableArray *imgData;
@property (strong, nonatomic) RPLiverCheckBean *graftingCheck;//移植检查数据模型

@property (nonatomic, strong) NSMutableDictionary *picCacheDic;//uiimage的缓存
@property (nonatomic, strong) NSMutableArray *picCacheArr;//UIImageView的缓存
@property (nonatomic, strong) NSMutableDictionary *imgPickerDic;
@property (strong, nonatomic) NSDictionary *picPropertyNameDic;//数据类型是图片的属性名称数组
@property (strong, nonatomic) NSMutableDictionary *picPropertyIndexDic;//图片类型属性名称及索引
//医院搜索相关
@property (nonatomic, strong) NSArray *commonHospitalArr;//常用医院
@property (nonatomic, retain) NSArray *hospitalArr;//所有医院
@property (nonatomic, retain) NSMutableArray *tobeChoosenArr;//备选医院
@property (nonatomic, assign) BOOL isSearched;//搜索状态
//地区选择相关
@property (nonatomic,strong) NSArray *cityArr; // 解析出来的最外层数组
@property (nonatomic,strong) NSArray *provinceArr; // 省
@property (nonatomic,strong) NSArray *countryArr; // 市
@property (nonatomic,strong) NSArray *districtArr; // 区
@property (nonatomic,strong) NSMutableArray *districtArr1;
@property (nonatomic,strong) NSMutableArray *districtIDArr;
@property (nonatomic,assign) NSInteger index1; // 省下标
@property (nonatomic,assign) NSInteger index2; // 市下标
@property (nonatomic,assign) NSInteger index3; // 区下标
@property (nonatomic,strong) ActionSheetCustomPicker *city_picker; // 选择器
@property (nonatomic,strong)NSMutableArray *districtTreeRaw;
@property (nonatomic,strong) NSArray *selections; //!< 选择的三个下标
@property (nonatomic,strong) NSIndexPath *tempIndexPath;
@property (nonatomic,strong) NSArray *misteryArray;//蜜汁数组
@end

@implementation YZEGanzangCheckViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //样式设置
    self.title = @"肝脏移植检查记录";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"返回"]
                                                                            style:UIBarButtonItemStylePlain
                                                                           target:self action:@selector(backAction)];
    UIBarButtonItem *submit = [[UIBarButtonItem alloc] initWithTitle:@"提交"
                                                               style:UIBarButtonItemStyleDone
                                                              target:self
                                                              action:@selector(submit)];
    self.navigationItem.rightBarButtonItem = submit;
    
    [self initData];
    [self initUI];
    
    if (_isAdd) {
        _graftingCheck = [RPLiverCheckBean new]; //新增检查记录，初始化模型
        RPUserInfoBean *myinfo = [RPUserInfoBean mj_objectWithKeyValuesAdd:[UserDefaultsTools getUserDefaultsForKey:USERINFO_KEY]];
        _graftingCheck.lgcName = myinfo.user.firstName;
        _graftingCheck.gender = myinfo.gender;
        _graftingCheck.tel1 = myinfo.phone;
        _graftingCheck.birthday = myinfo.birthday;
        _graftingCheck.districtsDTO = myinfo.district;
        _graftingCheck.address = myinfo.address;
        [self getHostpitalData];
    }
    else {
        [[YZENetwork sharedInstace]getRequestWithUrl:[NSString stringWithFormat:@"%@%@/%ld", BASE, URL_GetGraftingcheckdata, _graftingId]
                                          parameters:nil
                                            delegate:self
                                          requestTag:1
                                        successBlock:^(id responseObject)
        {
            self.graftingCheck = [RPLiverCheckBean mj_objectWithKeyValuesAdd:responseObject];
            [self.tableView reloadData];
            [self getHostpitalData];
        }];
    }
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)submit{
    if (_heightTF.text.length>0) {
        _graftingCheck.height = _heightTF.text;
    }
    if (_weightTF.text.length>0) {
        _graftingCheck.weight = _weightTF.text;
    }
    NSDictionary *paramDic = _graftingCheck.mj_keyValuesAdd;
    if (_isAdd) {
        [[YZENetwork sharedInstace] postRequestWithUrl:[BASE stringByAppendingString:URL_GetGraftingcheckdata]
                                            parameters:paramDic
                                              delegate:self
                                            requestTag:2
                                          successBlock:^(id responseObject)
        {
            [QMUITips showSucceed:@"已提交数据" inView:self.view hideAfterDelay:1];
            [self backAction];
        }];
    }
    else {
        [[YZENetwork sharedInstace] putRequestWithUrl:[BASE stringByAppendingString:URL_GetGraftingcheckdata]
                                           parameters:paramDic
                                             delegate:self
                                           requestTag:2
                                         successBlock:^(id responseObject)
        {
            [QMUITips showSucceed:@"已提交数据" inView:self.view hideAfterDelay:1];
            [self backAction];
        }];
    }
}
- (IBAction)OnInputEnd:(UITextField *)sender {
    UIView *cell = [[sender superview]  superview];
    [_graftingCheck setValue:sender.text forKey:cell.accessibilityIdentifier];
}

#pragma mark - 业务逻辑
- (void)initData{
    self.picCacheArr = [NSMutableArray array];
    self.picCacheDic = [NSMutableDictionary dictionary];
}

- (void)initUI{
    //整理单选按钮
    self.m1 = [[RadioButtonManager alloc]initWithData:self.optypeBtnArr
                                                 vals:@[@"DCD肝移植", @"活体肝移植"]
                                              OnClick:^(NSString * val)
    {
        _graftingCheck.operationWay = val;
    }];
    self.m2 = [[RadioButtonManager alloc]initWithData:self.graftingstandardBtnArr
                                                 vals:@[@"经典原位移植", @"背驮式", @"改良背驮式"]
                                            OnClick:^(NSString *val)
    {
        _graftingCheck.graftingStandard = val;
    }];
    self.m3 = [[RadioButtonManager alloc]initWithData:self.fitypeBtnArr
                                                 vals:@[@"端端吻合", @"胆肠吻合", @"端端吻合放T管"]
                                              OnClick:^(NSString *val)
    {
        _graftingCheck.bileDuct = val;
    }];
}
//往UI元素填数据
- (void)writeData:(UITableViewCell*)cell indexpath:(NSIndexPath*)indexPath{
    if (indexPath.section==1 && (indexPath.row==5 || indexPath.row==6)) {
            _heightTF.text = _graftingCheck.height;
            _weightTF.text = _graftingCheck.weight;
    }
    else if (indexPath.section==1 && indexPath.row==2){
        NSString *gender = @"男";
        if ([_graftingCheck.gender isEqualToString:@"FEMALE"]) {
            gender = @"女";
        }
        cell.detailTextLabel.text = gender;
    }
    else if (indexPath.section==1 && indexPath.row==4){
        NSString *communidateAddress;
        if ([_graftingCheck.districtsDTO.city.province.name isEqualToString:_graftingCheck.districtsDTO.city.name]) {
            communidateAddress = [NSString stringWithFormat:@"%@%@",
                                  _graftingCheck.districtsDTO.city.name?_graftingCheck.districtsDTO.city.name:@"",
                                  _graftingCheck.districtsDTO.name?_graftingCheck.districtsDTO.name:@""];
        }
        else {
            communidateAddress = [NSString stringWithFormat:@"%@%@%@",
                                        _graftingCheck.districtsDTO.city.province.name?_graftingCheck.districtsDTO.city.province.name:@"",
                                        _graftingCheck.districtsDTO.city.name?_graftingCheck.districtsDTO.city.name:@"",
                                        _graftingCheck.districtsDTO.name?_graftingCheck.districtsDTO.name:@""];
        }
        cell.detailTextLabel.text = communidateAddress?communidateAddress:@" ";
        
    }
    else if (indexPath.section==2 && indexPath.row==1){ //手术医院
        cell.detailTextLabel.text = _graftingCheck.hospitalDTO.name?_graftingCheck.hospitalDTO.name:@" ";
    }
    else if (indexPath.section==2 && indexPath.row==6){ //手术方式
        [_m1 setChoosen:_graftingCheck.operationWay];
        [_m2 setChoosen:_graftingCheck.graftingStandard];
        [_m3 setChoosen:_graftingCheck.bileDuct];
    }
    else if ((indexPath.section==3 || indexPath.section==6) && indexPath.row!=0){ //病理结果和出院小结
        NSInteger index = ROWINDEX(indexPath);
        DzyImgPicker *picker = [cell viewWithTag:index]; //图片选择控件
        if (!picker) {
            picker = [[DzyImgPicker alloc] initWithFrame:CGRectMake(10, 5, SCREEN_WIDTH-20, 100) andParentV:self andMaxNum:3];
            picker.tag = index;
            picker.dzyImgDelegate = self;
            [cell.contentView addSubview:picker];
            [self.picPropertyIndexDic setObject:cell.accessibilityIdentifier forKey:[NSNumber numberWithInteger:picker.tag]];
        }
        NSString *urlStr = [_graftingCheck valueForKey:cell.accessibilityIdentifier];
        if (!_picCacheDic[[NSNumber numberWithInteger:index]]) {
            [self requestPictures:urlStr ctrlIndex:indexPath];
        }
    }
    else if (indexPath.row!=0){
        NSString *val = [_graftingCheck valueForKey:cell.accessibilityIdentifier];
        cell.detailTextLabel.text = val?val:@" ";
    }
}

//发起图片请求
- (void)requestPictures:(NSString*)urlArrStr ctrlIndex:(NSIndexPath*)indexPath{
    if (![urlArrStr isNotEmpty]) {
        return;
    }
    NSMutableArray *urlArr = [[urlArrStr componentsSeparatedByString:@","] mutableCopy];
    if (((NSString*)urlArr.lastObject).length==0) {
        [urlArr removeLastObject];
    }
    NSMutableArray *tempImageArr = [NSMutableArray array];
    for (NSString *url in urlArr) {
        NSURL *ourl = [NSURL URLWithString:url];
        UIImageView *iv = [[UIImageView alloc] init];
        [_picCacheArr addObject:iv];
        [iv sd_setImageWithURL:ourl completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (image) {
                [tempImageArr addObject:image];
                if (tempImageArr.count == urlArr.count) {
                    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                    DzyImgPicker *picker = [cell viewWithTag:ROWINDEX(indexPath)];
                    [picker giveImages:tempImageArr];
                }
            }
        }];
    }
    [_picCacheDic setObject:@1 forKey:[NSNumber numberWithInteger:10000*indexPath.section+indexPath.row]];
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return  10;
}

//每次cell进入可见区域都会调用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    [self writeData:cell indexpath:indexPath];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"" delegate:self];
        [picker setTag:ROWINDEX(indexPath)];
        [picker setActionSheetPickerStyle:IQActionSheetPickerStyleDatePicker];
        [picker show];
    }
    else if (indexPath.section==1){
        switch (indexPath.row) {
            case 0:
                break;
            case 1:
                [self goSinglelineFormView:indexPath];
                break;
            case 2:
            {
                IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"" delegate:self];
                picker.titleFont = [UIFont systemFontOfSize:12];
                picker.titleColor = [UIColor redColor];
                [picker setTag:ROWINDEX(indexPath)];
                [picker setTitlesForComponents:@[self.genderArr]];
                [picker show];
            }
                break;
            case 3:
            {
                IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"" delegate:self];
                [picker setTag:ROWINDEX(indexPath)];
                [picker setActionSheetPickerStyle:IQActionSheetPickerStyleDatePicker];
                [picker show];
            }
                break;
            case 4://地区
            {
                self.city_picker = [[ActionSheetCustomPicker alloc]initWithTitle:@"选择地区" delegate:self showCancelButton:YES origin:self.view initialSelections:@[@(self.index1),@(self.index2),@(self.index3)]];
                self.city_picker.tapDismissAction  = TapActionSuccess;
                // 可以自定义左边和右边的按钮
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                button.frame = CGRectMake(0, 0, 44, 44);
                [button setTitle:@"取消" forState:UIControlStateNormal];
                UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
                [button1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                button1.frame = CGRectMake(0, 0, 44, 44);
                [button1 setTitle:@"确定" forState:UIControlStateNormal];
                [self.city_picker setCancelButton:[[UIBarButtonItem alloc] initWithCustomView:button]];
                [self.city_picker setDoneButton:[[UIBarButtonItem alloc] initWithCustomView:button1]];
                [self.city_picker showActionSheetPicker];
                self.tempIndexPath = indexPath;
            }
                break;
            case 7:
            case 8:
            case 9:
            case 10:
            case 11:
            {
                [self goSinglelineFormView:indexPath];
            }
                break;
            default:
                break;
        }
    }
    else if (indexPath.section==2){
        switch (indexPath.row) {
            case 1:{
                [self goSearchHospital];
            }
                break;
            case 2:
            {
                [self goSinglelineFormView:indexPath];
            }
                break;
            case 3:
            case 4:
            case 5:
            {
                IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"" delegate:self];
                [picker setTag:ROWINDEX(indexPath)];
                [picker setActionSheetPickerStyle:IQActionSheetPickerStyleDatePicker];
                [picker show];
            }
                break;
            default:
                break;
        }
    }
    else if (indexPath.section==4){
        switch (indexPath.row) {
            case 0://标题
                break;
            case 1:
            {
                RoutineBloodViewController *v = [RoutineBloodViewController new];
                v.delegate = self;
                v.routineBlood = _graftingCheck.routineBloodDTO;
                [self.navigationController pushViewController:v animated:YES];
            }
                break;
            case 2:
            {
                LiverViewController *v = [LiverViewController new];
                v.delegate = self;
                v.liver = _graftingCheck.liverDTO;
                [self.navigationController pushViewController:v animated:YES];
            }
                break;
            case 3:
            {
                RenalViewController *v = [RenalViewController new];
                v.delegate = self;
                v.renal = _graftingCheck.renalDTO;
                [self.navigationController pushViewController:v animated:YES];
            }
                break;
            case 4:
            {
                BloodsugarViewController *v = [BloodsugarViewController new];
                v.delegate = self;
                v.bloodsugar = _graftingCheck.bloodSugarDTO;
                [self.navigationController pushViewController:v animated:YES];
            }
                break;
            case 5:
            {
                BloodfatViewController *v = [BloodfatViewController new];
                v.delegate = self;
                v.bloodfat = _graftingCheck.bloodFatDTO;
                [self.navigationController pushViewController:v animated:YES];
            }
            case 6:
            {
                ElectrolyteViewController *v = [ElectrolyteViewController new];
                v.delegate = self;
                v.electrolyte = _graftingCheck.electrolyteDTO;
                [self.navigationController pushViewController:v animated:YES];
            }
                break;
            case 7:
            {
                HepatitisVirusViewController *v = [HepatitisVirusViewController new];
                v.delegate = self;
                v.hepatitisVirus = _graftingCheck.hepatitisDTO;
                [self.navigationController pushViewController:v animated:YES];
            }
                break;
            case 8:
            {
                TumorMarkerViewController *v = [TumorMarkerViewController new];
                v.delegate = self;
                v.tumormarker = _graftingCheck.tumorMarkerDTO;
                [self.navigationController pushViewController:v animated:YES];
            }
                break;
            case 9:
            {
                ImSupViewController *v = [ImSupViewController new];
                v.delegate = self;
                v.imsup = _graftingCheck.imSupConcentrationDTO;
                [self.navigationController pushViewController:v animated:YES];
            }
                break;
            case 10:
            {
                LiverTranSonoViewController *v = [LiverTranSonoViewController new];
                v.delegate = self;
                v.livertransono = _graftingCheck.liverTranSonoDTO;
                [self.navigationController pushViewController:v animated:YES];
            }
            default:
                break;
        }
    }
    else if (indexPath.section==5){
        TabletPlanViewController *v = [TabletPlanViewController new];
        v.delegate = self;
        v.isOnlyLocal = YES;
        UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:v];
        [self presentViewController:navi animated:YES completion:nil];
    }
}

- (void)goSinglelineFormView:(NSIndexPath *)indexPath{
    SinglelineTextFormViewController *v =[SinglelineTextFormViewController new];
    v.delegate = self;
    v.indexPath = indexPath;
    [self.navigationController pushViewController:v animated:YES];
}

#pragma mark - 图片选择控件代理
- (void)getBase64Images:(NSArray *)imgData index:(NSInteger)tag{
    NSString *key = [self.picPropertyNameDic objectForKey:[self.picPropertyIndexDic objectForKey:[NSNumber numberWithInteger:tag]]];
    [_graftingCheck setValue:imgData forKey:key];
}

#pragma mark - 各子view返回数据用的代理
//RoutineBloodViewControllerDelegate
- (void)backRoutinebloodData:(RPOutinebloodBean *)data{
    _graftingCheck.routineBloodDTO = data;
}
//LiverViewControllerDelegate
- (void)backLiver:(RPLiverBean *)data{
    _graftingCheck.liverDTO = data;
}
//RenalViewControllerDelegate
- (void)backRenal:(RPRenalBean *)data{
    _graftingCheck.renalDTO = data;
}
//BloodsugarViewControllerDelegate
- (void)backBloodsugar:(RPBloodsugar *)data{
    _graftingCheck.bloodSugarDTO = data;
}
//BloodfatViewControllerDelegate
- (void)backBloodfat:(RPBloodfatBean *)data{
    _graftingCheck.bloodFatDTO = data;
}
//
//ElectrolyteViewControllerDelegate
- (void)backElectrolyte:(RPElectrolyteBean *)data{
    _graftingCheck.electrolyteDTO = data;
}
//HepatitisViewDelegate
- (void)backHepatitisVirus:(RPHepatitisVirusBean *)data{
    _graftingCheck.hepatitisDTO = data;
}
//TumorMarkerViewControllerDelegate
- (void)backTumormarker:(RPTumormarkerBean *)data{
    _graftingCheck.tumorMarkerDTO = data;
}
//ImSupViewControllerDelegate
- (void)backImSup:(RPImSupConcentrationBean *)data{
    _graftingCheck.imSupConcentrationDTO = data;
}
//LiverTranSonoViewControllerDelegate
- (void)backLiverTransono:(RPLiverTranSonoBean *)data{
    _graftingCheck.liverTranSonoDTO = data;
}

#pragma mark - IQActionSheetPickerViewDelegate
- (void)actionSheetPickerView:(IQActionSheetPickerView *)pickerView didSelectTitles:(NSArray<NSString *> *)titles{
    NSString *valstr = [titles componentsJoinedByString:@""];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:DEROWINDEX(pickerView.tag)];
    cell.detailTextLabel.text = valstr;
    [_graftingCheck setValue:valstr forKey:cell.accessibilityIdentifier];
}

- (void)actionSheetPickerView:(IQActionSheetPickerView *)pickerView didSelectDate:(NSDate *)date{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:DEROWINDEX(pickerView.tag)];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterNoStyle];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    cell.detailTextLabel.text=[formatter stringFromDate:date];
    [_graftingCheck setValue:cell.detailTextLabel.text forKey:cell.accessibilityIdentifier];
}

#pragma mark - SinglelineTextFormViewControllerDelegate
- (void)backData:(NSString *)content identifier:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.detailTextLabel.text = content;
    [_graftingCheck setValue:content forKey:cell.accessibilityIdentifier];
}
#pragma mark TabletPlanViewBackDelegate
- (void)backTabletPlan:(RPMedicinePlan *)plan index:(long)index{
    _graftingCheck.sickMedicinePlanDTO = plan;
}


-(void)goSearchHospital{
    //创建控制器
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:nil searchBarPlaceholder:NSLocalizedString(@"搜索医院",@"搜索类型") didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        for (RPHospitalInfo *hospital in self.hospitalArr) {
            if ([hospital.name isEqualToString:searchText]) {
                self.graftingCheck.hospitalDTO.ID = hospital.ID;
                self.graftingCheck.hospitalDTO.name = hospital.name;
                _ophospitalCell.detailTextLabel.text = self.graftingCheck.hospitalDTO.name;
            }
        }
        [searchViewController dismissViewControllerAnimated:YES completion:nil];
    }];
    // 4. 设置代理
    searchViewController.delegate = self;
    searchViewController.dataSource = self;
    searchViewController.showSearchHistory = NO;
    [searchViewController setSearchSuggestionHidden:NO];
    searchViewController.cancelButton.tintColor = [UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1];
    searchViewController.cancelButton.title = @"取消";
    searchViewController.suggestionViewCellSeperatorStyle = UITableViewCellSeparatorStyleSingleLine;
    // 5. 跳转到搜索控制器
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    
    [self presentViewController:nav animated:YES completion:^{
        [searchViewController showSuggestionWhenLoaded];//加载即显示searchSuggestion
    }];
}

#pragma mark - PYSearchSuggestionViewDataSource
- (UITableViewCell*)searchSuggestionView:(UITableView *)searchSuggestionView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    if (_isSearched) {
        cell.textLabel.text = self.tobeChoosenArr[indexPath.row];
    }
    else {
        RPHospitalInfo *hospital;
        if (indexPath.section==0) {
            hospital = self.commonHospitalArr[indexPath.row];
        }
        else {
            hospital = self.hospitalArr[indexPath.row];
        }
        cell.textLabel.text = hospital.name;
    }
    return cell;
}

- (NSInteger)searchSuggestionView:(UITableView *)searchSuggestionView numberOfRowsInSection:(NSInteger)section{
    if (_isSearched) {
        return self.tobeChoosenArr.count;
    }
    else {
        NSInteger number = 0;
        if (section==0) {
            number = self.commonHospitalArr.count;
        }
        else {
            number = self.hospitalArr.count;
        }
        return number;
    }
    
}

- (NSInteger)numberOfSectionsInSearchSuggestionView:(UITableView *)searchSuggestionView{
    if (_isSearched) {
        return 1;
    }
    else
        return 2;
}

- (CGFloat)searchSuggestionView:(UITableView *)searchSuggestionView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

- (CGFloat)searchSuggestionView:(UITableView *)searchSuggestionView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

- (UIView *)searchSuggestionView:(UITableView *)searchSuggestionView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, searchSuggestionView.frame.size.width, 30)];
    header.backgroundColor = COLOR_BG_GRAY;
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, header.width-10, header.height)];
    title.font = [UIFont systemFontOfSize:14];
    title.textAlignment = NSTextAlignmentLeft;
    title.textColor = BLACK_COLOR;
    if (section==0) {
        if (_isSearched) {
            title.text = @"搜索到如下结果";
        }
        else {
            title.text = @"常用医院";
        }
    }
    else {
        title.text = @"所有医院";
    }
    [header addSubview:title];
    
    return header;
}

#pragma mark - PYSearchViewControllerDelegate
//在这里进行搜索操作
- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)seachBar searchText:(NSString *)searchText
{
    if (searchText.length>0 && ![searchText isEqualToString:@" "]) {
        /**改用搜索本地数据
         // 开始搜索执行以下代码
         NSString *path=[[BASE stringByAppendingString:URL_SearchHospital] stringByAppendingString:searchText];
         //如果网址中出现了 中文 需要进行URL编码
         path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
         */
        self.isSearched = YES;
        //后台线程搜索
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tobeChoosenArr removeAllObjects];
            for (RPHospitalInfo *hospital in self.hospitalArr) {
                if ([hospital.name rangeOfString:searchText].location!=NSNotFound) {
                    [self.tobeChoosenArr addObject:hospital.name];
                }
            }
            [searchViewController.searchSuggestionView reloadData];
        });
    }
    else{
        self.isSearched = NO;
        [searchViewController.searchSuggestionView reloadData];
    }
}

//获取医院列表
- (void)getHostpitalData{
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_SuggestionHospital] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        self.commonHospitalArr = [RPHospitalInfo mj_objectArrayWithKeyValuesArrayAdd:responseObject[@"common"]];
        self.hospitalArr = [RPHospitalInfo mj_objectArrayWithKeyValuesArrayAdd:responseObject[@"all"]];
        for (RPHospitalInfo *h in _hospitalArr) {
            [self.tobeChoosenArr addObject:h.name];
        }
        self.isSearched = NO;
        [self calculateFirstData];
    }];
}

#pragma mark - 配置基本数据数组
-(NSArray*)genderArr{
    if (!_genderArr) {
        _genderArr = @[@"男", @"女"];
    }
    return _genderArr;
}
- (NSDictionary *)picPropertyNameDic{
    if (!_picPropertyNameDic) {
        _picPropertyNameDic = @{@"pathologyResult":@"pathologyResults", @"summary":@"summaries"};
    }
    return _picPropertyNameDic;
}
- (NSMutableDictionary *)picPropertyIndexDic{
    if (!_picPropertyIndexDic) {
        _picPropertyIndexDic = [NSMutableDictionary dictionary];
    }
    return _picPropertyIndexDic;
}



#pragma mark 地区选择相关
//加载城市json
- (void)loadFirstData
{
    NSMutableArray *firstName = [[NSMutableArray alloc] init];
    for (NSDictionary *dict in self.districtTreeRaw)
    {
        NSString *name = dict[@"provinceName"];
        [firstName addObject:name];
    }
    // 第一层是省份 分解出整个省份数组
    self.provinceArr = firstName;
}

// 根据传进来的下标数组计算对应的三个数组
- (void)calculateFirstData
{
    self.districtTreeRaw = [[NSMutableArray alloc] initWithContentsOfFile:[[DataUtils getDocumentsPath] stringByAppendingPathComponent:DISTRICTREE_PLISTNAME]];
    // 拿出省的数组
    [self loadFirstData];
    
    NSMutableArray *cityNameArr = [[NSMutableArray alloc] init];
    // 根据省的index1，默认是0，拿出对应省下面的市
    for (NSDictionary *cityName in self.districtTreeRaw[self.index1][@"citys"]) {
        
        NSString *name1 = cityName[@"cityName"];
        [cityNameArr addObject:name1];
    }
    // 组装对应省下面的市
    self.countryArr = cityNameArr;
    //                             index1对应省的字典         市的数组 index2市的字典   对应市的数组
    // 这里的allValue是取出来的大数组，取第0个就是需要的内容
    
    self.districtArr = self.districtTreeRaw[self.index1][@"citys"][self.index2][@"districts"];
    [self.districtArr1 removeAllObjects];
    [self.districtIDArr removeAllObjects];
    for (NSDictionary *dic in self.districtArr) {
        [self.districtArr1 addObject:dic[@"districtName"]];
        [self.districtIDArr addObject:dic[@"districtID"]];
    }
}

#pragma mark 地区选择相关 - UIPickerViewDelegate Implementation
#pragma mark 地区选择相关 - UIPickerViewDataSource Implementation
//返回pickerview列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}
//返回pickerview某列行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    // Returns
    switch (component)
    {
        case 0: return self.provinceArr.count;
        case 1: return self.countryArr.count;
        case 2:return self.districtArr1.count;
        default:break;
    }
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component)
    {
        case 0: return self.provinceArr[row];break;
        case 1: return self.countryArr[row];break;
        case 2:return self.districtArr1[row];break;
        default:break;
    }
    return nil;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel* label = (UILabel*)view;
    if (!label)
    {
        label = [[UILabel alloc] init];
        [label setFont:[UIFont systemFontOfSize:14]];
    }
    
    NSString * title = @"";
    switch (component)
    {
        case 0: title =   self.provinceArr[row];break;
        case 1: title =   self.countryArr[row];break;
        case 2: title =   self.districtArr1[row];break;
        default:break;
    }
    label.textAlignment = NSTextAlignmentCenter;
    label.text=title;
    return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (component)
    {
        case 0:
        {
            self.index1 = row;
            self.index2 = 0;
            self.index3 = 0;
            //            [self calculateData];
            // 滚动的时候都要进行一次数组的刷新
            [self calculateFirstData];
            [pickerView reloadComponent:1];
            [pickerView reloadComponent:2];
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [pickerView selectRow:0 inComponent:2 animated:YES];
        }
            break;
            
        case 1:
        {
            self.index2 = row;
            self.index3 = 0;
            //            [self calculateData];
            [self calculateFirstData];
            [pickerView selectRow:0 inComponent:2 animated:YES];
            [pickerView reloadComponent:2];
        }
            break;
        case 2:
            self.index3 = row;
            break;
        default:break;
    }
}

- (void)configurePickerView:(UIPickerView *)pickerView
{
    pickerView.showsSelectionIndicator = NO;
}
// 点击done的时候回调
- (void)actionSheetPickerDidSucceed:(ActionSheetCustomPicker *)actionSheetPicker origin:(id)origin
{
    NSMutableString *detailAddress = [[NSMutableString alloc] init];
    if (self.index1 < self.provinceArr.count) {
        NSString *firstAddress = self.provinceArr[self.index1];
        [detailAddress appendString:firstAddress];
    }
    if (self.index2 < self.countryArr.count) {
        NSString *secondAddress = self.countryArr[self.index2];
        [detailAddress appendString:secondAddress];
    }
    if (self.index3 < self.districtArr1.count) {
        NSString *thirfAddress = self.districtArr1[self.index3];
        [detailAddress appendString:thirfAddress];
        
        self.graftingCheck.districtsDTO.id=[self.districtIDArr[self.index3] longValue];
    }
    self.graftingCheck.districtsDTO.name = self.districtArr1[self.index3];
    self.graftingCheck.districtsDTO.city.name = self.countryArr[self.index2];
    self.graftingCheck.districtsDTO.city.province.name = self.provinceArr[self.index1];
    [self.tableView reloadData];
}


- (NSArray *)provinceArr
{
    if (_provinceArr == nil) {
        _provinceArr = [[NSArray alloc] init];
    }
    return _provinceArr;
}
-(NSArray *)countryArr
{
    if(_countryArr == nil)
    {
        _countryArr = [[NSArray alloc] init];
    }
    return _countryArr;
}

- (NSArray *)districtArr
{
    if (_districtArr == nil) {
        _districtArr = [[NSArray alloc] init];
    }
    return _districtArr;
}
- (NSMutableArray *)districtArr1
{
    if (_districtArr1 == nil) {
        _districtArr1 = [[NSMutableArray alloc] init];
    }
    return _districtArr1;
}
- (NSMutableArray *)districtIDArr
{
    if (_districtIDArr == nil) {
        _districtIDArr = [[NSMutableArray alloc] init];
    }
    return _districtIDArr;
}
-(NSArray *)cityArr
{
    if (_cityArr == nil) {
        _cityArr = [[NSArray alloc] init];
    }
    return _cityArr;
}

#pragma mark 网络请求通用处理
- (void)OnSuccess:(id)responseObject requestTag:(int)tag{
    
}

- (void)OnStartWithRequestTag:(int)tag{
    [QMUITips showLoadingInView:self.view];
}
- (void)OnFinishWithRequestTag:(int)tag{
    [QMUITips hideAllToastInView:self.view animated:YES];
}
- (void)OnFail:(NSString *)errorMsg errorCode:(NSInteger)errorCode requestTag:(int)tag{
    [QMUITips showError:errorMsg inView:self.view hideAfterDelay:1];
}

@end
